<!--
 * @Author: yanjikun
 * @Date: 2022-04-24 14:55:55
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-05-11 17:30:56
 * @Description: file content
-->
<template>
  <Input v-bind="bindValues" :value="labelValue">
    <template #addonAfter>
      <Popover v-model:visible="visible" trigger="click" placement="topRight">
        <template #content>
          <div class="select-icon-box">
            <i
              v-for="item in glyphs"
              :key="item.icon_id"
              :title="item.name"
              class="select-icon-box-item"
              @click="handleIconSelect(item)"
              :class="{ active: modelValue?.replace(css_prefix_text, '') == item.font_class }"
            >
              <IconFont :type="item.font_class" :prefix="css_prefix_text" size="22"></IconFont>
            </i>
          </div>
        </template>
        <SettingOutlined class="cursor-pointer" />
      </Popover>
    </template>
    <template v-if="modelValue" #prefix>
      <IconFont :type="modelValue" :prefix="css_prefix_text" size="16" />
    </template>
  </Input>
</template>

<script setup lang="ts">
  import { iconsSelectProps } from '../types/components'
  import icons from '@/assets/json/icons.json'
  import IconFont from '@/components/IconFont'
  import { SettingOutlined } from '@ant-design/icons-vue'
  import { useVModel } from '@vueuse/core'
  import { ref, computed, unref } from 'vue'
  import { Input, Popover } from 'ant-design-vue'
  defineOptions({
    name: 'IconsSelect',
  })

  const { glyphs, css_prefix_text } = icons
  interface Emits {
    (e: 'update:value', val: string): void
  }
  const props = defineProps(iconsSelectProps)

  const bindValues = computed(() => {
    return {
      ...props,
      disabled: true,
      placeholder: '请选择图标',
    }
  })
  const emit = defineEmits<Emits>()

  const visible = ref(false)

  const modelValue = useVModel(props, 'value', emit)

  const labelValue = computed(() => {
    return glyphs.find((item) => item.font_class === unref(modelValue))?.name
  })

  const handleIconSelect = (iconItem: typeof glyphs[number]) => {
    visible.value = false
    modelValue.value = iconItem.font_class
  }
</script>

<style scoped lang="less">
  .select-icon-box {
    @apply flex flex-wrap flex-row max-h-300px overflow-auto w-280px;

    &-item {
      @apply flex m-2px p-6px cursor-pointer;
      border: 1px solid #e5e7eb;

      &:hover,
      &.active {
        @apply border-blue-500;
        border-color: var(--ant-primary-color);
      }
    }
  }
</style>
